Today you will
Repeat code with loops: a checkout that keeps taking items, and a price table in three lines.
- Repeat code with a
whileloop and stop it withbreak. - Repeat a set number of times with
forandrange(). - Keep a running total in a loop.
- Recognise and fix a loop that never stops.
Deep dive A: why do we need loops?
A loop repeats code for us. Without one, printing a countdown means typing the same line over and over:
print("Patties left: 3")
print("Patties left: 2")
print("Patties left: 1")
print("Sold out")Patties left: 3
Patties left: 2
Patties left: 1
Sold outThat works for 3, but what about 300? Or when we don't know how many times in advance, like a checkout where the customer keeps adding items? A loop does the repeating, however many times it takes.
stock = 3
while stock > 0:
print("Patties left:", stock)
stock = stock - 1
print("Sold out")Patties left: 3
Patties left: 2
Patties left: 1
Sold outDeep dive B: the while loop - repeat as long as...
while works like an if that keeps coming back. It checks the condition; if it's True, it runs the indented block, then goes back to the top and checks again. It stops the moment the condition is False.
Same four parts as an if: the word while, a condition, a colon, and an indented block.
count = 1
while count <= 3:
print("Round", count)
count = count + 1
print("Finished, count is now", count)Round 1
Round 2
Round 3
Finished, count is now 4Trace it round by round - this is how to read any loop:
| Round | count at the top | count <= 3 ? | What happens |
|---|---|---|---|
| 1 | 1 | True | prints Round 1, count becomes 2 |
| 2 | 2 | True | prints Round 2, count becomes 3 |
| 3 | 3 | True | prints Round 3, count becomes 4 |
| - | 4 | False | loop ends, jump to the last line |
Deep dive C: counters and running totals
A counter goes up by 1 each time round the loop. A running total adds a new amount each time. Both use the same trick: the variable appears on both sides of =.
count = count + 1 means: take the old value of count, add 1, and store the answer back in count.
total = 0
items = 0
total = total + 5.00 # beef patty
items = items + 1
total = total + 4.00 # coconut tart
items = items + 1
print(items, "items, total EC$", total)2 items, total EC$ 9.0Shortcut: total += 5 means exactly the same as total = total + 5. You'll see it a lot in real code. -= works for taking away.
stock = 10
stock -= 3 # same as stock = stock - 3
stock += 5 # delivery arrived
print("Stock:", stock)Stock: 12Deep dive D: loops that never stop (and how to escape)
If the condition never becomes False, the loop runs forever. This is called an infinite loop. The usual cause: nothing inside the loop changes the variable in the condition.
stock = 3
while stock > 0:
print("Patties left:", stock)
stock = stock - 1 # without this line, stock is always 3 - forever!
print("Sold out")Patties left: 3
Patties left: 2
Patties left: 1
Sold outTo stop a runaway program: press Ctrl + C in the terminal, or the red Stop button in Thonny. Every programmer does this regularly - it's not a disaster.
Deep dive E: while True and break
while True: means "loop forever" - the condition is always True. We use it when we don't know when to stop until something happens inside the loop, like the customer typing done.
break jumps straight out of the loop, to the first line after it.
count = 0
while True:
count = count + 1
print("Scanning item", count)
if count == 3:
print("Last item - stopping")
break
print("Checkout finished")Scanning item 1
Scanning item 2
Scanning item 3
Last item - stopping
Checkout finishedThat's exactly how the checkout works: while True keeps asking for prices, and if entry == "done": break is the way out. Notice float(entry) - prices have cents, so we convert to a float, not an int.
Deep dive F: the for loop and range()
for repeats once for each item in a sequence. With range(), that sequence is a set of numbers, so it's perfect when you know how many times to repeat.
for qty in range(1, 4):
print("Order of", qty)Order of 1
Order of 2
Order of 3Each time round, the variable qty takes the next number automatically - no counter to add to, so no risk of an infinite loop.
The rules of range():
| Code | Gives | Why |
|---|---|---|
range(5) | 0, 1, 2, 3, 4 | starts at 0, stops BEFORE 5 |
range(1, 6) | 1, 2, 3, 4, 5 | start at 1, stop BEFORE 6 |
range(0, 20, 5) | 0, 5, 10, 15 | third number is the step |
range(5, 0, -1) | 5, 4, 3, 2, 1 | a negative step counts down |
print(list(range(5)))
print(list(range(1, 6)))
print(list(range(0, 20, 5)))
print(list(range(5, 0, -1)))[0, 1, 2, 3, 4]
[1, 2, 3, 4, 5]
[0, 5, 10, 15]
[5, 4, 3, 2, 1]week = 0
for qty in range(7, 365, 7): # Range first then the STEP or Gap
week += 1
print("Day Number", qty, " is in Week Number", week)Day Number 7 is in Week Number 1
Day Number 14 is in Week Number 2
Day Number 21 is in Week Number 3
...
Day Number 364 is in Week Number 52for also works on text, one letter at a time:
for letter in "PATTY":
print(letter) P
A
T
T
Yuse .lower() or .upper() to change the case of the letters. mini string manipulation
Deep dive G: while or for - which one?
| Use | When | Shop example |
|---|---|---|
for | You know how many times (or have a set of things) | Print prices for 1 to 10 patties |
while | You repeat until something happens | Keep taking items until the customer says done |
Both can do the same job, but the right one makes the code shorter and safer. Compare these two countdowns:
# with while: you manage the counter yourself
n = 3
while n > 0:
print(n)
n = n - 1
# with for: range does it for you
for n in range(3, 0, -1):
print(n)3
2
1
3
2
1Deep dive H: lining up the price table
The price table uses two new f-string tricks to make neat columns:
{qty:>3}- make it 3 characters wide and push it to the right (>= right,<= left){price:6.2f}- 6 characters wide, 2 decimal places
price = 5.00
for qty in [1, 10, 100]:
print(f"no width: {qty} patties")
for qty in [1, 10, 100]:
print(f"width 3: {qty:>3} patties EC${qty * price:7.2f}")no width: 1 patties
no width: 10 patties
no width: 100 patties
width 3: 1 patties EC$ 5.00
width 3: 10 patties EC$ 50.00
width 3: 100 patties EC$ 500.00The two format codes
" 1", 10 becomes " 10", and 100 becomes "100". Every value takes up exactly 3 characters, which is why the columns line up." 5.00" is 3 spaces plus 4 characters." 50.00" is 2 spaces plus 5 characters." 500.00" is 1 space plus 6 characters.1. The checkout loop
Type a few prices, then type done.
# shop.py - Module 4: a checkout that keeps going until "done"
total = 0
items = 0
while True:
entry = input("Item price (or 'done'): ")
if entry == "done":
break
total = total + float(entry)
items = items + 1
print(f" Running total: EC${total:.2f}")
print(f"{items} items. Total: EC${total:.2f}")2. A price table with for
Three lines of loop make a whole table.
# Module 4 - a price list for 1 to 10 patties with a for loop
price = 5.00
print("Qty Price")
for qty in range(1, 11):
print(f"{qty:>3} EC${qty * price:6.2f}")Words to know
| Word | Meaning |
|---|---|
| Loop | Code that repeats |
while | Repeat as long as a condition is True |
for | Repeat once for each item or number |
range(1, 11) | The numbers 1 to 10 |
break | Leave the loop now |
| Running total | A variable that grows each time round the loop |
Bug hunt
This loop never stops. Press Ctrl+C, then fix it so it counts down 5, 4, 3, 2, 1 and says "Sold out".
# BUG HUNT - this loop never stops! (press Ctrl+C to stop it)
# Fix it so it counts down 5, 4, 3, 2, 1 and then says "Sold out".
stock = 5
while stock > 0:
print("Patties left:", stock)
print("Sold out")Hints (open only if stuck)
- What needs to change each time round the loop?
- Take 1 away from stock inside the loop.
Practice
Homework 4 (5%): stock.py
Simulate a day's stock. It must:
Submit your .py file and a screenshot of it running, before the next module.
| Mark | Means |
|---|---|
| 5 | Runs and has everything |
| 3 | Runs with parts missing, or has errors |
| 1 | Started |
| 0 | Not submitted |
Quiz 4
Check yourself here, then take the graded quiz in the quiz section of robotics.a3tech.uk (two tries).
ADDITIONAL - STREAMLIT APP - SNEAK PEEK 4
The price table as a web page. A slider picks how many rows, and the same for loop builds the table.
# price_table_app.py - a for loop in a Streamlit app
# Run it with: streamlit run price_table_app.py
import streamlit as st
st.title("Mama J's Bakery - Price Table")
price = 5.00
max_qty = st.slider("Show prices up to how many patties?", min_value=1, max_value=24, value=10)
for qty in range(1, max_qty + 1):
st.write(f"{qty} patties: EC${qty * price:.2f}")See the browser. Drag the slider - e.g. at 3:
1 patties: EC$5.00
2 patties: EC$10.00
3 patties: EC$15.00Your mission today
Store a whole route in a list, follow it step by step, and play with words.
Follow a route
The route is a list of words. The loop does one step at a time.
# Module 4 - Follow a route stored in a list (elif)
route = ["forward", "left", "forward", "right", "forward"]
print("This route has", len(route), "steps. First step:", route[0])
for step in route:
print("Doing:", step)
if step == "forward":
robot.set_motors(50, 50)
robot.wait(1000)
elif step == "left":
robot.set_motors(-50, 50)
robot.wait(400)
elif step == "right":
robot.set_motors(50, -50)
robot.wait(400)
robot.stop()Words and countdowns
Change the callsign to yours.
# Module 4 - Words (strings) and counting with range
callsign = "falcon"
print("Pilot:", callsign.upper()) # FALCON
print("Callsign has", len(callsign), "letters")
for countdown in range(3, 0, -1): # 3, 2, 1 (step of -1)
print(countdown)
print("Go!")
robot.set_motors(60, 60)
robot.wait(1500)
robot.stop()Robot words
| Code | What it means |
|---|---|
route[0] | The first item in the list (lists start at 0) |
len(route) | How many items are in the list |
elif | Else if: check another choice |
| String | Text in quotes |
.upper() | Makes text CAPITALS |
range(3, 0, -1) | Counts 3, 2, 1 |
Challenges
Try one at a time. Change the code, run it, and watch.
Challenge puzzle
What will this print?
route = ["forward", "left", "forward"]
print(route[1])Show the answer
left (lists start counting at 0)Build puzzle
Add the missing line so "back" works.
elif step == "back":
______
robot.wait(1000)Show the answer
robot.set_motors(-50, -50)Quiz 4
Pass with 3 out of 5. Then take it for points in the quiz section of robotics.a3tech.uk.